﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using FastReflectionLib;
using Newtonsoft.Json;
using QJY.Data;
using System.Data;
using Newtonsoft.Json.Linq;
using System.Net;
using System.IO;
using Newtonsoft.Json.Converters;

using QJY.Common;
using System.DirectoryServices;
using Senparc.Weixin.QY.AdvancedAPIs;
using Senparc.Weixin.QY.Entities;
using Senparc.Weixin.QY.CommonAPIs;

namespace QJY.API
{
    public class Commanage : IWsService
    {
        public void ProcessRequest(HttpContext context, ref Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            MethodInfo methodInfo = typeof(Commanage).GetMethod(msg.Action.ToUpper());
            Commanage model = new Commanage();
            methodInfo.FastInvoke(model, new object[] { context, msg, P1, P2, UserInfo });
        }


        #region 官网登录和注册





        /// <summary>
        /// 发送手机验证码
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void SENDCHKMSG(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            //if (!string.IsNullOrEmpty(P1))
            //{
            //    string code = CommonHelp.numcode(4);
            //    try
            //    {
            //        string type = context.Request["type"] ?? "";
            //        string content = "";
            //        switch (type)
            //        {
            //            case "changeadmin":
            //                content = "您更换超级管理员的验证码为：" + code + "，如非本人操作，请忽略本短信";
            //                break;
            //            default:
            //                content = "注册验证码：" + code + "，如非本人操作，请忽略本短信";
            //                break;

            //        }

            //        CommonHelp.SendSMS(P1, content, 0);
            //        msg.Result = CommonHelp.GetMD5(code);
            //    }
            //    catch
            //    {
            //        msg.ErrorMsg = "发送验证码失败";
            //    }
            //}
        }
        public void YDL(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string loginIP = System.Configuration.ConfigurationManager.AppSettings["LoginIP"];
            if (!string.IsNullOrEmpty(loginIP))
            {
                string strIP = CommonHelp.getIP(context);//用户IP
                if (!strIP.Contains(loginIP))
                {
                    msg.ErrorMsg = "您的IP无法登录此网站!";
                    return;
                }

            }




            string domain = System.Configuration.ConfigurationManager.AppSettings["AD_Domain"];
            try
            {
                string strUserName = P1;
                JH_Auth_QY qyModel = new JH_Auth_QYB().GetALLEntities().First();

                JH_Auth_User userInfo = new JH_Auth_User();
                if (strUserName == "administrator")
                {
                    string password = CommonHelp.GetMD5(P2);

                    userInfo = new JH_Auth_UserB().GetEntity(d => d.UserPass == password && d.UserName == "administrator");
                    if (string.IsNullOrEmpty(userInfo.pccode))
                    {
                        userInfo.pccode = CommonHelp.CreatePCCode(userInfo);
                    }
                    userInfo.logindate = DateTime.Now;
                    new JH_Auth_UserB().Update(userInfo);
                    msg.Result = userInfo.pccode;
                    msg.Result1 = userInfo.UserName;
                    msg.Result2 = qyModel.FileServerUrl;
                    msg.Result4 = userInfo;
                }
                else
                {
                    LDAPHelper ldap = new LDAPHelper();
                    var ldapUser = ldap.GetUser(P1);

                    var authResult = false;
                    if (ldapUser == null)
                    {
                        authResult = false;
                    }
                    else
                    {
                        LDAPUserStatus status = ldap.Authenticate(ldapUser, P2);
                        if (status != LDAPUserStatus.Success)
                        {
                            authResult = false;
                        }
                        else
                        {
                            authResult = true;
                        }
                    }
                    if (!authResult)
                    {
                        msg.ErrorMsg = "找不到域帐号信息啊";
                    }
                    else
                    {

                        //根据域账户找到微信对应账户信息
                        string strUser = new OUTManage().GetWXUserByYUser(strUserName);
                        //
                        List<JH_Auth_User> userList = new JH_Auth_UserB().GetEntities(d => d.UserName == strUser).ToList();
                        if (userList.Count() == 0)
                        {
                            msg.ErrorMsg = "用户信息不存在";
                        }
                        else
                        {
                            userInfo = userList[0];
                            if (userInfo.IsUse != "Y")
                            {
                                msg.ErrorMsg = "用户被禁用,请联系管理员";
                            }
                            if (msg.ErrorMsg == "")
                            {
                                if (string.IsNullOrEmpty(userInfo.pccode))
                                {
                                    userInfo.pccode = CommonHelp.CreatePCCode(userInfo);
                                }
                                userInfo.logindate = DateTime.Now;
                                new JH_Auth_UserB().Update(userInfo);
                                msg.Result = userInfo.pccode;
                                msg.Result1 = userInfo.UserName;
                                msg.Result2 = qyModel.FileServerUrl;
                                msg.Result4 = userInfo;
                            }

                        }
                    }
                }


            }
            catch (Exception ex)
            {
            }
        }

        public void RTXDL(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strUserID = P1;
            string url = System.Configuration.ConfigurationManager.AppSettings["RTXIP"] + "/checkapi.php?";
            url += "id=" + strUserID + "&sign=" + P2;
            //url = url.Replace(" ", "%2B");
            var request = (HttpWebRequest)WebRequest.Create(url);
            var response = (HttpWebResponse)request.GetResponse();
            string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            if (responseString == "ok")
            {
                JH_Auth_QY qyModel = new JH_Auth_QYB().GetALLEntities().First();
                string strUser = new OUTManage().GetWXUserByYUser(strUserID);
                //
                List<JH_Auth_User> userList = new JH_Auth_UserB().GetEntities(d => d.UserName == strUser).ToList();
                if (userList.Count() == 0)
                {
                    msg.ErrorMsg = "用户信息不存在";
                }
                else
                {
                    JH_Auth_User userInfo = new JH_Auth_User();
                    userInfo = userList[0];
                    if (userInfo.IsUse != "Y")
                    {
                        msg.ErrorMsg = "用户被禁用,请联系管理员";
                    }
                    if (msg.ErrorMsg == "")
                    {
                        if (string.IsNullOrEmpty(userInfo.pccode))
                        {
                            userInfo.pccode = CommonHelp.CreatePCCode(userInfo);
                        }
                        userInfo.logindate = DateTime.Now;
                        new JH_Auth_UserB().Update(userInfo);
                        msg.Result = userInfo.pccode;
                        msg.Result1 = userInfo.UserName;
                        msg.Result2 = qyModel.FileServerUrl;
                        msg.Result4 = userInfo;
                    }

                }
            }
            else
            {
                msg.ErrorMsg = "";
            }
        }



        /// <summary>
        /// 验证企业名称
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void YZQYMC(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {

            if (!string.IsNullOrEmpty(P1))
            {
                var qy = new JH_Auth_QYB().GetEntity(p => p.QYName == P1);
                if (qy != null)
                {
                    msg.ErrorMsg = "企业名称已存在";
                }
            }
        }


        #endregion






        #region 分享查看文档操作
        /// <summary>
        /// 获取文档资源
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETWDZY(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strWDYM = CommonHelp.GetConfig("WDYM");

            FT_File ff = new FT_FileB().GetEntities(p => p.YLCode == P1).FirstOrDefault();
            if (ff != null)
            {
                msg.Result = strWDYM + ff.YLPath;
                msg.Result1 = ff.YLCount;
                msg.Result2 = ff.Name + "." + ff.FileExtendName;

            }
            else
            {
                msg.ErrorMsg = "此文件不存在或您没有权限！";
            }
        }
        public void GETSHAREINFO(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int ID = 0;
            int.TryParse(P1, out ID);
            if (ID > 0)
            {
                FT_File_Share Model = new FT_File_ShareB().GetEntity(d => d.ID == ID);


                if (Model.SharePasd == P2 || Model.ShareType == "0")//公开链接或者输入提取码正确
                {
                    string strSql = string.Format(@"SELECT qy.QYName,qy.LogoID,share.CRUserName,share.RefType,share.ShareDueDate,share.CRDate,CASE WHEN share.RefType='file' then f.Name+'.'+f.FileExtendName WHEN share.RefType='wj'  THEN folder.Name END Name 
                                            ,CASE WHEN share.RefType='file' then f.ID WHEN share.RefType='wj'  THEN folder.ID END  ID ,f.FileExtendName,f.FileSize,share.ComId,f.ISYL,f.FileMD5,qy.FileServerUrl,f.YLUrl
                                            from FT_File_Share share INNER join JH_Auth_QY  qy on share.ComId=qy.ComId
                                            LEFT join FT_File f on share.RefID=f.ID and share.ComId=f.ComId and share.RefType='file'
                                            LEFT join  FT_Folder folder on share.RefID=folder.ID and share.RefType='wj' where share.ID={0} and share.IsDel!='Y'", ID);
                    DataTable dt = new FT_File_ShareB().GetDTByCommand(strSql);
                    if (dt.Rows.Count > 0)
                    {
                        DateTime dueDate = DateTime.Now;
                        if (DateTime.TryParse(dt.Rows[0]["ShareDueDate"].ToString(), out dueDate) && dueDate > DateTime.Now)
                        {
                            msg.Result = dt;
                        }
                        else
                        {
                            msg.ErrorMsg = "分享已过期";
                        }
                    }
                    else
                    {
                        msg.ErrorMsg = "分享已取消";
                    }
                }
                else
                {
                    msg.Result = 1;
                    msg.ErrorMsg = "提取码有误，请重新输入";
                }

            }
        }
        //分享页面根据文件夹Id获取文件列表
        public void GETFILELIST(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int FolderID = int.Parse(P1);//
            int ComId = int.Parse(P2);
            msg.Result = new FT_FolderB().GetEntities(d => d.ComId == ComId && d.PFolderID == FolderID);
            msg.Result1 = new FT_FileB().GetEntities(d => d.ComId == ComId && d.FolderID == FolderID);
            return;
        }


        /// <summary>
        /// 判断是否公开链接
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void ISPUBLIC(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int ID = int.Parse(P1);//
            FT_File_Share Model = new FT_File_ShareB().GetEntity(d => d.ID == ID && d.IsDel != "Y");
            msg.Result = Model.ShareType;
        }
        /// <summary>
        /// 向服务器发送压缩目录命令
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">目录ID</param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void COMPRESSFOLDER(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strCode = P1;
            int ComId = int.Parse(P2);
            FT_FolderB.FoldFile Mode = new FT_FolderB.FoldFile();
            Mode.FolderID = -1;
            Mode.Name = "压缩文件";
            Mode.SubFileS = new List<FT_File>();
            Mode.SubFolder = new List<FT_FolderB.FoldFile>();
            foreach (string item in P1.SplitTOList(','))
            {
                int FileID = int.Parse(item.Split('|')[0].ToString());
                string strType = item.Split('|')[1].ToString();
                if (item.Split('|')[1].ToString() == "file")
                {
                    FT_File file = new FT_FileB().GetEntity(d => d.ID == FileID);
                    file.YLUrl = "";
                    Mode.SubFileS.Add(file);
                }
                else
                {
                    List<FT_FolderB.FoldFileItem> ListID = new List<FT_FolderB.FoldFileItem>();
                    FT_FolderB.FoldFile obj = new FT_FolderB().GetWDTREE(FileID, ref ListID, ComId);
                    Mode.SubFolder.Add(obj);
                }
            }
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            string Result = JsonConvert.SerializeObject(Mode, Newtonsoft.Json.Formatting.Indented, timeConverter).Replace("null", "\"\"");
            JH_Auth_QY qymodel = new JH_Auth_QYB().GetEntity(d => d.ComId == ComId);
            //压缩文件
            Dictionary<String, String> DATA = new Dictionary<String, String>();
            DATA.Add("data", Result);
            HttpWebResponse ResponseData = CommonHelp.CreatePostHttpResponse(qymodel.FileServerUrl.TrimEnd('/') + "/" + qymodel.QYCode + "/document/zipfolder", DATA, 0, "", null);
            string strData = CommonHelp.GetResponseString(ResponseData);
            msg.Result = strData;
        }

        /// <summary>
        /// 获取页面html(excel)
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETHTML(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strWDYM = CommonHelp.GetConfig("WDYM");

            FT_File ff = new FT_FileB().GetEntities(p => p.YLCode == P1).FirstOrDefault();
            if (ff != null)
            {
                //定义局部变量
                HttpWebRequest httpWebRequest = null;
                HttpWebResponse httpWebRespones = null;
                Stream stream = null;
                string htmlString = string.Empty;
                string url = strWDYM + ff.YLPath;

                //请求页面
                try
                {
                    httpWebRequest = WebRequest.Create(url + ".html") as HttpWebRequest;
                }
                //处理异常
                catch
                {
                    msg.ErrorMsg = "建立页面请求时发生错误！";
                }
                httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; Maxthon 2.0)";
                //获取服务器的返回信息
                try
                {
                    httpWebRespones = (HttpWebResponse)httpWebRequest.GetResponse();
                    stream = httpWebRespones.GetResponseStream();
                }
                //处理异常
                catch
                {
                    msg.ErrorMsg = "接受服务器返回页面时发生错误！";
                }

                StreamReader streamReader = new StreamReader(stream, System.Text.Encoding.UTF8);
                //读取返回页面
                try
                {
                    htmlString = streamReader.ReadToEnd();
                }
                //处理异常
                catch
                {
                    msg.ErrorMsg = "读取页面数据时发生错误！";
                }
                //释放资源返回结果
                streamReader.Close();
                stream.Close();

                msg.Result = htmlString;
                msg.Result1 = url;

            }
            else
            {
                msg.ErrorMsg = "此文件不存在或您没有权限！";
            }
        }
        #endregion


        /// <summary>
        /// 根据ID查询工资明细
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETGZDLIST(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int ID;
            JH_Auth_User userInfo = new JH_Auth_User();
            int.TryParse(context.Request["ID"] ?? "-1", out ID);
            msg.Result = new SZHL_XZ_GZDB().GetEntities(d => d.ID == ID).ToList();
            return;
        }


        public void SENDMSG(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strTAG = context.Request["TAG"] ?? "-1";
            string XXcorpId = System.Configuration.ConfigurationManager.AppSettings["XXcorpId"];
            string XXSecret = System.Configuration.ConfigurationManager.AppSettings["XXSecret"];
            string XXAppID = System.Configuration.ConfigurationManager.AppSettings["XXAppID"];
            string strMsgUser = context.Request["MsgUserS"] ?? "-1";
            string strMsgText = context.Request["MsgText"] ?? "";

            AccessTokenResult Token = CommonApi.GetToken(XXcorpId, XXSecret);
            MassApi.SendText(Token.access_token, strMsgUser, "", "", XXAppID, strMsgText);

            // MassApi.SendNews(Token.access_token, th.UserS.Replace(',', '|'), "", "", app.AppID, th.MODEL);

        }


    }
}